//
//  DGGlobalTimerTask.m
//  DGGlobalTimer
//
//  Created by Jinxiao on 7/25/14.
//  Copyright (c) 2014 debugeek. All rights reserved.
//

#import "DGGlobalTimerTask.h"
#import "DGGlobalTimerTaskManager.h"
#import "DGGlobalTimerObserverManager.h"

@interface DGGlobalTimerTask () <NSCoding>
@property (readwrite, nonatomic, retain) NSTimer *timer;
@end

@implementation DGGlobalTimerTask

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];

    if(self) {
        self.key = [aDecoder decodeObjectForKey:@"key"];
        self.duration = [aDecoder decodeDoubleForKey:@"duration"];
        self.interval = [aDecoder decodeDoubleForKey:@"interval"];
        self.fired = [aDecoder decodeDoubleForKey:@"fired"];
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.key forKey:@"key"];
    [aCoder encodeDouble:self.duration forKey:@"duration"];
    [aCoder encodeDouble:self.interval forKey:@"interval"];
    [aCoder encodeDouble:self.fired forKey:@"fired"];
}

- (void)schedule {
    NSTimeInterval elapsed = [[NSDate date] timeIntervalSince1970] - _fired;
    NSTimeInterval remains = _duration - elapsed;

    if(remains <= 0) {
        [[DGGlobalTimerTaskManager sharedInstance] removeTimerTaskForKey:_key];
        [[DGGlobalTimerObserverManager sharedInstance] dispatchCompletedActionForKey:_key];
    } else {
        [[DGGlobalTimerObserverManager sharedInstance] dispatchInitializedActionForKey:_key remains:_duration];

        [_timer invalidate];
        _timer = [NSTimer scheduledTimerWithTimeInterval:_interval target:self selector:@selector(timerDidTick) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
}

- (void)drop {
    [self dropForced:NO];
}

- (void)dropForced:(BOOL)forced {
    [_timer invalidate];
    [[DGGlobalTimerTaskManager sharedInstance] removeTimerTaskForKey:_key];

    if(forced) {
        [[DGGlobalTimerObserverManager sharedInstance] dispatchPreparedActionForKey:_key];
    } else {
        [[DGGlobalTimerObserverManager sharedInstance] dispatchCompletedActionForKey:_key];
    }
}

- (void)timerDidTick {
    NSTimeInterval elapsed = [[NSDate date] timeIntervalSince1970] - _fired;
    NSTimeInterval remains = _duration - elapsed;

    [[DGGlobalTimerObserverManager sharedInstance] dispatchTriggeredActionForKey:_key remains:remains];

    if(remains <= 0) {
        [self drop];
    }
}

- (NSTimeInterval)remains {
    NSTimeInterval elapsed = [[NSDate date] timeIntervalSince1970] - _fired;
    NSTimeInterval remains = _duration - elapsed;

    return remains;
}

@end
